<template>
    <div>
        <el-dialog v-model="dialogVisible" width="80%" align-center :close-on-click-modal="false" :show-close="false"
            :before-close="handleClose" destroy-on-close draggable>
            <template #header="{ close }">
                <div class="dialog-header flex justify-between items-center">
                    <div>申报材料{{ ruleForm.id ? '编辑' : '新增' }}</div>
                    <el-icon class="el-icon--left cursor-pointer" @click="close">
                        <CircleCloseFilled color="#fff" />
                    </el-icon>
                </div>
            </template>
            <el-form :model="ruleForm" :rules="rules" label-width="130px" ref="ruleFormRef">
                <!-- 基本信息 -->
                <div class="bg-white mt-[10px]">
                    <BaseHead>基本信息</BaseHead>
                    <div class="p-[10px]">

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="奖励名称">
                                    {{ ruleForm.honorName }}
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="奖励级别">
                                    {{ formatHonorLevelId(ruleForm.honorLevel) }}
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="成果名称" prop="productName">
                                    <el-input placeholder="请输入成果名称" v-model="ruleForm.productName" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属单位" prop="unitId">
                                    <el-select v-model="ruleForm.unitId" disabled placeholder="请选择所属单位" clearable>
                                        <el-option v-for="item in zcgsdwList" :key="item.codeColumn"
                                            :label="item.valueColumn" :value="item.codeColumn" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="申请日期" prop="applyDate">
                                    <el-date-picker v-model="ruleForm.applyDate" type="date" format="YYYY/MM/DD"
                                        value-format="YYYY-MM-DD" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="学科名称" prop="subjectId">
                                    <el-select v-model="ruleForm.subjectId" placeholder="请选择获奖级别" clearable>
                                        <el-option v-for="item in kjxkflList" :key="item.id" :label="item.label"
                                            :value="item.id" />
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="完成单位">
                                    <el-input placeholder="请输入完成单位" v-model="ruleForm.completeUnit"
                                        clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="成果形式">
                                    <el-input placeholder="请输入成果形式" v-model="ruleForm.productMode" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="申请书附件">
                                    <FileUpload :uploadUrl="uploadUrl" :limit="2" tip="最多可上传2个附件,每个附件大小不超过20M"
                                        v-model="fileList" @change="fileChange">
                                    </FileUpload>
                                </el-form-item>
                            </el-col>

                            <el-col :span="24">
                                <el-form-item label="备注">
                                    <el-input v-model="ruleForm.note" type="textarea" />
                                </el-form-item>
                            </el-col>


                        </el-row>

                    </div>
                </div>
                <!-- 完成人信息 -->
                <div class="bg-white mt-[10px]">
                    <BaseHead>完成人信息
                        <template v-slot:Rslot>
                            <el-button @click="addHonor">添加</el-button>
                        </template>
                    </BaseHead>
                    <div class="p-[10px]">
                        <el-table :data="tableData" border style="width: 100%">
                            <el-table-column align="center" type="index" label="署名顺序" width="80" />
                            <el-table-column align="center" prop="date" label="完成人类型">
                                <template #default="scope">
                                    <el-select v-model="scope.row.authorType"
                                        :disabled="scope.row.disable || scope.$index == 0" @change="e => {
            selectAuthorType(e, scope.$index);
        }">
                                        <el-option v-for="item in wcrTypelist" :key="item.code" :label="item.name"
                                            :value="item.code" />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" prop="name" label="完成人姓名">
                                <template #default="scope">
                                    <el-select v-model="scope.row.authorName"
                                        :disabled="scope.row.disable || scope.$index == 0" @change="e => {
            selectAuthor(e, scope.$index, scope.row);
        }" v-if="scope.row.authorType != '3'" filterable remote reserve-keyword placeholder="请输入关键字检索"
                                        :remote-method="remoteMethod" :loading="loading">
                                        <el-option v-for="item in options" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                    <!-- <el-autocomplete v-model="scope.row.authorName" v-else placeholder="请输入关键字检索"
                                        value-key="label" :fetch-suggestions="querySearchAsync"
                                        @select="e => { handleSelect(e, scope.$index) }" /> -->
                                    <el-input v-model="scope.row.authorName" v-else />
                                </template>
                            </el-table-column>
                            <el-table-column align="center" prop="address" label="性别">
                                <template #default="scope">
                                    <el-select v-model="scope.row.sexId">
                                        <el-option label="男" value="1" />
                                        <el-option label="女" value="0" />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" prop="address" label="学历">
                                <template #default="scope">
                                    <el-select v-model="scope.row.eduLevelId">
                                        <el-option v-for="item in xlList" :key="item.code" :label="item.name"
                                            :value="item.code" />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" prop="address" label="工作单位">
                                <template #default="scope">
                                    <el-input v-model="scope.row.authorUnit" v-if="scope.row.authorType == '3'" />
                                    <el-select v-model="scope.row.authorUnitId" :disabled="scope.row.authorType == '1'"
                                        @change="e => {
            changUnit(e, scope.$index);
        }" v-else placeholder=" 请选择所属单位" clearable>
                                        <el-option v-for=" item in sydwList" :key="item.codeColumn"
                                            :label="item.valueColumn" :value="item.codeColumn" />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" prop="address" label="职称">
                                <template #default="scope">
                                    <el-tree-select v-model="scope.row.titleId" node-key="id" :data="zcList"
                                        :render-after-expand="false" :props="defaultProps" />
                                </template>
                            </el-table-column>
                            <el-table-column align="center" prop="address" label="贡献率（%）">
                                <template #default="scope">
                                    <el-input placeholder="" v-model.number="scope.row.workRatio" @input="e => {
            handleInput1(e, scope.$index);
        }
            " type="number">
                                    </el-input>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" prop="address" label="操作">
                                <template #default="scope">

                                    <el-link type="primary" :underline="false"
                                        v-if="!scope.row.disable && scope.$index != 0"
                                        @click="delHonor(scope.$index)">删除</el-link>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <div class="operate-btns">
                        <el-button type="primary" :loading="btnLoading"
                            @click="zcsubmitForm(ruleFormRef)">暂存</el-button>
                        <el-button type="primary" :loading="btnLoading" @click="submitForm(ruleFormRef)">提交</el-button>
                        <el-button type="primary" @click="closeMet">关闭</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import { getPersonDetails } from "@/api/achievement/common.js"
import { useRouter, useRoute } from "vue-router";
import { honorApplyBookAdd, gethonorApplyBookUpdate } from "@/api/achievement/cghj"
import FileUpload from "@/views/achievement/components/FileUpload.vue"
import { ElMessage, ElMessageBox } from "element-plus";
import _ from 'lodash';

const route = useRoute();
const dialogVisible = defineModel();
const props = defineProps({
    hjztList: Array,
    hjjbList: Array,
    zcgsdwList: Array,
    sydwList: Array,
    kjxkflList: Array,
    xlList: Array,
    zcList: Array,
    planInfo: Object
})
const defaultProps = {
    children: 'children',
    label: 'label',
}
const tableData = reactive([
    {
        authorType: '1',
        eduLevelId: '',
        authorName: '',
        titleId: '',
        authorUnit: '',
        authorUnitId: '',
        workRatio: null,
        personId: '',   //userId
        orderId: 1,
        authorAccount: "",   //职工号
        sexId: '',
        subjectId: ""
    },
]);
const addHonor = () => {
    tableData.push({
        authorType: '1',
        eduLevelId: '',
        authorName: '',
        titleId: '',
        authorUnit: '',
        authorUnitId: '',
        sexId: '',
        workRatio: null,
        personId: '',   //userId
        orderId: tableData.length ? tableData[tableData.length - 1].orderId + 1 : 1,
        authorAccount: "",   //职工号
        sexId: '',
        subjectId: ""
    })
}
const delHonor = (index) => {
    tableData.splice(index, 1)
}
const selectAuthorType = (e, index) => {
    let type1 = tableData[index].authorType
    let orderId1 = tableData[index].orderId
    tableData[index] = {
        authorType: type1,
        eduLevelId: '',
        authorName: '',
        titleId: '',
        authorUnit: '',
        authorUnitId: '',
        sexId: '',
        workRatio: null,
        personId: '',   //userId
        orderId: orderId1,
        authorAccount: "",   //职工号
        sexId: '',
        subjectId: ""
    }
    if (e == '3') {
        tableData[index].personId = '3'
    }
}
const wcrTypelist = reactive([
    {
        code: '1',
        name: '教师'
    },
    {
        code: '2',
        name: '学生'
    },
    {
        code: '3',
        name: '校外'
    },
]);

const ruleForm = reactive({
    name: '',
    applyInfoId: '',
    honorName: '',
    honorLevel: '',
    productName: '',
    unitId: '',
    subjectId: '',
    completeUnit: '',
    productMode: '',
    note: '',
    fileIds: "",
    applyDate: "",
})
const rules = reactive({
    productName: [
        { required: true, message: '请输入成果名称', trigger: 'blur' },
    ],
    honorName: [
        { required: true, message: '请输入奖励名称', trigger: 'blur' },
    ],
    unitId: [
        {
            required: true,
            message: '请选择所属单位',
            trigger: 'change',
        },
    ],
    subjectId: [
        {
            required: true,
            message: '请选择学科名称',
            trigger: 'change',
        },
    ],
    applyDate: [
        {
            required: true,
            message: '请选择申请日期',
            trigger: 'change',
        },
    ],

})

const formatHonorLevelId = (cellValue) => {
    if (props.hjjbList.length && cellValue) {
        return props.hjjbList.find(item => item.code == cellValue).name
    } else {
        return ''
    }


}
const handleInput = (value) => {
    if (value !== null) { // 检查是否为null（非数字）或已经是数字且在范围内
        ruleForm.scale = Math.max(0, Math.min(100, value)); // 确保值在0到100之间
    } else {
        ruleForm.scale = null; // 重置为null，或者你可以设置为一个默认值，比如0或空字符串，取决于你的需求
    }
};
const handleInput1 = (value, index) => {
    if (value !== null) { // 检查是否为null（非数字）或已经是数字且在范围内
        tableData[index].workRatio = Math.max(0, Math.min(100, value)); // 确保值在0到100之间
    } else {
        tableData[index].workRatio = null; // 重置为null，或者你可以设置为一个默认值，比如0或空字符串，取决于你的需求
    }
};
const subType = ref(1)

const querySearchAsync = (queryString, cb) => {
    console.log(queryString, 'queryString')
    if (queryString) {
        let pamrs = {
            name: queryString
        }
        getPersonDetails(pamrs).then(res => {
            console.log(res, 'res')
            if (res.code == 200) {
                let arr = res.data;
                arr.map(item => {
                    item.value = item.name;
                    item.label = item.name;
                })
                cb(arr);
            }
        })
    } else {
        cb([]);
    }

    // const results = queryString
    //   ? links.value.filter(createFilter(queryString))
    //   : links.value

    // clearTimeout(timeout)
    // timeout = setTimeout(() => {
    //   cb(results)
    // }, 3000 * Math.random())
}


const changecoType = () => {
    if (ruleForm.cooperationType == 1) {
        ruleForm.scale = null
    }
}
const handleSelect = (item) => {
    console.log(item)
    tableData[index].personId = item.id
    tableData[index].authorAccount = item.account
    tableData[index].sexId = item.sexId
    tableData[index].subjectId = item.subjectId
    tableData[index].authorUnitId = item.unitId
    tableData[index].authorUnit = item.unitName
    tableData[index].eduLevelId = item.eduLevelId
    tableData[index].titleId = item.titleId
}
const changUnit = (value, index) => {
    console.log(value, 'unitvalue')
    if (item) {
        tableData[index].authorUnit = zcgsdwList.value.find(item => item.codeColumn == value).valueColumn
    }
}
const options = ref([])
const loading = ref(false)
const remoteMethod = (query) => {
    if (query) {
        loading.value = true
        let pamrs = {
            name: query
        }
        getPersonDetails(pamrs).then(res => {
            console.log(res, 'res')
            if (res.code == 200) {
                let arr = res.data;
                arr.map(item => {
                    item.value = item.name + ' ' + item.account + ' ' + item.unitName;
                    item.label = item.name + ' ' + item.account + ' ' + item.unitName;
                })
                options.value = arr
                loading.value = false
            }
        })
    } else {
        options.value = []
    }
}
// unit_id
const selectAuthor = (e, index, row) => {
    console.log(e, index, row)
    console.log(options.value.find(item => item.value == e))
    let userInfo = options.value.find(item => item.value == e)
    let cfuserInfo = tableData.find(item => item.personId == userInfo.id)
    if (cfuserInfo) {
        tableData[index].authorName = ''
        ElMessage({
            message: '此人已在列表中，请勿重复添加',
            type: 'error',
        })
        return;
    } else {
        tableData[index].authorName = userInfo.name
        tableData[index].personId = userInfo.id
        tableData[index].authorAccount = userInfo.account
        tableData[index].sexId = userInfo.sexId
        tableData[index].subjectId = userInfo.subjectId
        tableData[index].authorUnitId = userInfo.unitId
        tableData[index].authorUnit = userInfo.unitName
        tableData[index].eduLevelId = userInfo.eduLevelId
        tableData[index].titleId = userInfo.titleId
    }
}

const btnLoading = ref(false)

const ruleFormRef = ref()
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            let params = {
                ...ruleForm,
            }
            if (tableData.length == 0) {
                ElMessage({
                    message: '请添加至少一条完成人信息',
                    type: 'error',
                })
                return;
            } else if (tableData[0].authorName == '') {
                ElMessage({
                    message: '请添加至少一条完成人信息',
                    type: 'error',
                })
                return;
            } else {
                let ContributionRate = 0
                tableData.forEach(item => {
                    ContributionRate += item.workRatio
                })
                if (ContributionRate > 100) {
                    ElMessage({
                        message: '贡献率不能大于100',
                        type: 'error',
                    })
                    return;
                }
            }
            params.honorApplyBookMemberDTOs = tableData
            params.submitType = 1
            console.log(params, 'params')
            btnLoading.value = true;
            if (params.id) {
                params = _.omit(params, ['lastEditDate', 'checkdate', 'createDate']);
                gethonorApplyBookUpdate(params).then((res) => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        dialogVisible.value = false
                        initData()
                        emit('callBack', "")
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                    btnLoading.value = false;
                })
            } else {
                honorApplyBookAdd(params).then((res) => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        dialogVisible.value = false
                        initData()
                        emit('callBack', "")
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                    btnLoading.value = false;
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const zcsubmitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            let params = {
                ...ruleForm,
            }
            if (tableData.length == 0) {
                ElMessage({
                    message: '请添加至少一条完成人信息',
                    type: 'error',
                })
                return;
            } else if (tableData[0].authorName == '') {
                ElMessage({
                    message: '请添加至少一条完成人信息',
                    type: 'error',
                })
                return;
            } else {
                let ContributionRate = 0
                tableData.forEach(item => {
                    ContributionRate += item.workRatio
                })
                if (ContributionRate > 100) {
                    ElMessage({
                        message: '贡献率不能大于100',
                        type: 'error',
                    })
                    return;
                }
            }
            params.honorApplyBookMemberDTOs = tableData
            params.submitType = -1
            console.log(params, 'params')
            btnLoading.value = true;
            if (params.id) {
                params = _.omit(params, ['lastEditDate', 'checkdate', 'createDate']);
                gethonorApplyBookUpdate(params).then((res) => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        dialogVisible.value = false
                        initData()
                        emit('callBack', "")
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                    btnLoading.value = false;
                })
            } else {
                honorApplyBookAdd(params).then((res) => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        dialogVisible.value = false
                        initData()
                        emit('callBack', "")
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                    btnLoading.value = false;
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const emit = defineEmits(['callBack']);
const handleClose = (done) => {
    tableData.length = 0;
    tableData.push(
        {
            authorType: '1',
            eduLevelId: '',
            authorName: '',
            titleId: '',
            authorUnit: '',
            authorUnitId: '',
            workRatio: null,
            personId: '',   //userId
            orderId: 1,
            authorAccount: "",   //职工号
            sexId: '',
            subjectId: ""
        })
    Object.assign(ruleForm, {
        name: '',
        applyInfoId: '',
        honorName: '',
        honorLevel: '',
        productName: '',
        unitId: '',
        subjectId: '',
        completeUnit: '',
        productMode: '',
        note: '',
        fileIds: "",
        applyDate: "",
    })
    delete ruleForm.id;
    delete ruleForm.checkdate;
    fileList.value = [];
    emit('callBack', "")
    done()
}

const initData = () => {
    tableData.length = 0;
    tableData.push(
        {
            authorType: '1',
            eduLevelId: '',
            authorName: '',
            titleId: '',
            authorUnit: '',
            authorUnitId: '',
            workRatio: null,
            personId: '',   //userId
            orderId: 1,
            authorAccount: "",   //职工号
            sexId: '',
            subjectId: ""
        })
    Object.assign(ruleForm, {
        name: '',
        applyInfoId: '',
        honorName: '',
        honorLevel: '',
        productName: '',
        unitId: '',
        subjectId: '',
        completeUnit: '',
        productMode: '',
        note: '',
        fileIds: "",
        applyDate: "",
    })
    delete ruleForm.id;
    delete ruleForm.checkdate;
    fileList.value = [];
}
const closeMet = () => {
    initData()
    dialogVisible.value = false
}

const uploadUrl = `/commonFile/uploadFile?modelName=honorApplyBookApply`;
const fileList = ref([]);

//上传的文件改变
const fileChange = () => {
    const ids = fileList.value.map((item) => {
        const id = item.response ? item.response.data : item.id;
        return id;
    });
    ruleForm.fileIds = ids.join(",");
};

const getRuleForm = (i) => {
    if (i.honorApplyBookMemberVOs && i.honorApplyBookMemberVOs.length > 0) {
        console.log(tableData, 'tableData')
        tableData.length = 0; // 清空数组
        tableData.push(...i.honorApplyBookMemberVOs); // 添加新元素

    }
    for (const key in i) {
        ruleForm[key] = i[key];
    }
    if (i.fileList && i.fileList.length > 0) {
        fileList.value = i.fileList.map((item) => {
            return {
                name: item.fileName,
                id: item.id,
            };
        });
    }
    console.log(ruleForm, 'ruleForm')
}
watch(
    () => props.planInfo,
    (newValue) => {
        console.log(newValue, 'newValue')
        ruleForm.applyInfoId = newValue.id || ''
        ruleForm.honorName = newValue.honorName || ''
        ruleForm.honorLevel = newValue.honorLevel || ''
    },
    { deep: true, immediate: true }
);

const getKyryInfo = (i) => {
    if (i && i.length > 0) {
        console.log(tableData, 'tableData')
        tableData.length = 0;
        tableData.push(...i);
        if (i[0].authorUnitId) {
            ruleForm.unitId = i[0].authorUnitId
        }
    }
}




defineExpose({
    getRuleForm,
    getKyryInfo
})
</script>

<style scoped lang="scss">
@import url("@/views/achievement/index.scss");
</style>